<template>
  <el-scrollbar>
    <el-collapse class="legend-collapse">
      <el-collapse-item
        v-for="item in loadedLayers"
        :title="item.label"
        :name="item.label"
        :key="item.value"
      >
        <div
          class="legend-list"
          v-if="legendData[item.value]"
        >
          <div
            v-for="legendItem in legendData[item.value]"
            :key="legendItem.name"
            class="legend-list-item"
          >
            <el-image :src="legendItem.img" fit="none" />
            <span>{{ legendItem.name }}</span>
          </div>
        </div>
      </el-collapse-item>
    </el-collapse>
  </el-scrollbar>
</template>

<script>
import axios from 'axios'
import { getAction } from '@/utils/helper'

const mapViewer = {}
const _layerManager = {}

export default {
  name: 'Legend',
  inject: ['viewerId'],
  data() {
    return {
      loadedLayers: [],
      selectedLayer: '',
      legendData: {}
    }
  },
  async created() {
    const { toolManager, layerManager } = await getAction(
      this.viewerId
    )
    mapViewer[this.viewerId] = toolManager.viewer
    _layerManager[this.viewerId] = layerManager

    this.$bus.$on('removeAdd', () => {
      this.getLayers(true)
    })
    this.$bus.$on('removeLayer', () => {
      this.getLayers(true)
    })

    this.getLayers()
  },
  methods: {
    getLayers(chooseFirst) {
      const layerList = _layerManager[this.viewerId].layers
        .reverse()
        .filter((item) => item.type !== 'layer')
      // console.log('图层', layerList)
      this.loadedLayers.splice(0, this.loadedLayers.length)
      this.loadedLayers.push(
        ...layerList.map((item) => {
          return {
            label: item.title,
            value: item.id,
            data: item
          }
        })
      )
      if (chooseFirst) {
        if (this.loadedLayers.length > 0) {
          this.selectedLayer =
            this.loadedLayers[0] &&
            this.loadedLayers[0].value
        } else {
          this.selectedLayer = ''
        }
      } else {
        if (
          this.loadedLayers.every(
            (item) => item.value !== this.selectedLayer
          )
        ) {
          // 已选择的图层被移除
          this.selectedLayer =
            this.loadedLayers[0] &&
            this.loadedLayers[0].value
        }
      }

      this.loadedLayers.forEach((item) => {
        if (
          !this.legendData[item.data.id] ||
          this.legendData[item.data.id].length === 0
        ) {
          this.getLayerLegendData(item.data)
        }
      })
    },
    getLayerLegendData(layer) {
      console.log('layer', layer)
      this.legendData[layer.id] = []
      axios
        .get(layer.serviceUrl + '/layers.json')
        .then((res) => {
          if (res.data) {
            const subLayerNames = []
            const subLayers = []
            res.data[0].subLayers.layers.forEach(
              (subLayer) => {
                if (
                  subLayer.theme &&
                  subLayer.theme.items &&
                  subLayer.theme.items instanceof Array &&
                  subLayer.theme.items.length
                ) {
                  subLayerNames.push(
                    subLayer.name + '@@' + res.data[0].name
                  )
                  subLayers.push(subLayer)
                }
              }
            )
            console.log('subLayerNames', subLayerNames)
            subLayers.forEach((subLayer, subLayerIndex) => {
              subLayer.theme.items.forEach(
                (item, index) => {
                  this.legendData[layer.id].push({
                    name: item.caption,
                    img:
                      layer.serviceUrl +
                      '/layers/' +
                      subLayerNames[subLayerIndex] +
                      `/items/${index}/legend.png?width=30&height=30`
                  })
                }
              )
              this.$forceUpdate()
            })
          }
        })
        .catch((err) => {
          console.error('查询子图层失败', err)
        })
    }
  }
  // watch: {
  //   selectedLayer: {
  //     handler(val, oldVal) {
  //       if (val) {
  //         const find = this.loadedLayers.find(
  //           (item) => item.value === this.selectedLayer
  //         )
  //         if (find) {
  //           this.getLayerLegendData(find.data)
  //         }
  //       } else {
  //         console.log('clear legend')
  //         if (oldVal) {
  //           this.legendData[oldVal] = []
  //         }
  //       }
  //     }
  //   }
  // }
}
</script>

<style lang="scss" scoped>
.el-scrollbar {
  flex: 1;
}

::v-deep {
  .el-scrollbar__wrap {
    overflow-x: hidden;
  }

  .legend-collapse {
    background-color: transparent;
    border-top: none;
    border-bottom: none;
    margin: 0 16px;

    .el-collapse-item {
      background-color: transparent;

      .el-collapse-item__header {
        background-color: transparent;
        color: white;
        border-bottom: none;
      }

      .el-collapse-item__wrap {
        background-color: transparent;
        border-bottom: none;

        .el-collapse-item__content {
          padding-bottom: 0;
        }
      }
    }
  }

  .legend-list {
    display: flex;
    flex-direction: column;

    &-item {
      display: flex;
      align-items: center;

      &:not(:last-of-type) {
        margin-bottom: 15px;
      }

      .el-image {
        width: 20px;
        height: 20px;
        margin-right: 6px;
      }

      span {
        font-size: 14px;
        color: #d2e6f0;
      }
    }
  }
}
</style>
